package com.googlecode.gwtbb.client.shared.util;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Feb 5, 2009
 */
public class Converter {
	public static Short toShort(String shortStr) {
		return StringUtils.isEmpty(shortStr) ? null : Short.valueOf(shortStr);
	}

	public static Long toCents(String moneyStr) {
		if (StringUtils.isEmpty(moneyStr))
			return null;
		if (moneyStr.charAt(0) == '$')
			moneyStr = moneyStr.substring(1);
		// gwt currently doesn't support BigDecimal
		//return new BigDecimal(moneyStr).scaleByPowerOfTen(2).longValue();
		int pointIndex = moneyStr.indexOf('.');
		if (pointIndex < 0) {
			moneyStr += "00";
		} else {
			int precision = moneyStr.length() - pointIndex - 1;
			switch (precision) {
				case 0:
					moneyStr = moneyStr.substring(0, pointIndex) + "00";
					break;
				case 1:
					moneyStr = moneyStr.substring(0, pointIndex) + moneyStr.substring(pointIndex + 1, pointIndex + 2) + "0";
					break;
				case 2:
					moneyStr = moneyStr.substring(0, pointIndex) + moneyStr.substring(pointIndex + 1, pointIndex + 3);
					break;
				default:
					// todo round up if necessary
					moneyStr = moneyStr.substring(0, pointIndex) + moneyStr.substring(pointIndex + 1, pointIndex + 3);
			}
		}
		return Long.valueOf(moneyStr);
	}

	public static String toMoneyString(Long cents) {
		if (cents == null)
			return null;
		long dollars = cents / 100;
		long centsLeft = cents % 100;
		if (cents < 10)
			return dollars + ".0" + centsLeft;
		else
			return dollars + "." + centsLeft;
	}
}
